package com.qikecn.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;

public class FileUtilSave {
	private static final Log log = Log.getLog(FileUtilSave.class);
	private static FileUtilSave fileUtil = null;
	private static BufferedReader bufferedReader = null;
	private static StringBuffer stringBuffer = null;
	private Object obj = new Object();
	private static long lastModify = 0;
	private static long currentModify = 0;
	private static long refreshTime = 0;
	
	private FileOutputStream writerStream;
	private BufferedWriter writer;
	
	
	/**
	 * 获取实例
	 * @return
	 */
	public static synchronized FileUtilSave getInstance(){
		if(fileUtil == null){
			fileUtil = new FileUtilSave();
		}
		return fileUtil;
	}
	
	/**
	 * 获取文件内容
	 * @param path
	 * @return
	 */
	public String getFileContent(String path){
		synchronized (obj) {
			try{
				java.io.File file = new java.io.File(path);
				currentModify = file.lastModified();
				if(stringBuffer != null && !stringBuffer.equals("") && currentModify == lastModify && (System.currentTimeMillis() - refreshTime < 1000 * 60 * 5) ){
					System.out.println("retrun buffer");
					return stringBuffer.toString();
				}
				System.out.println("read file");
				bufferedReader = new BufferedReader(new FileReader(file));
				stringBuffer = new StringBuffer();
				String temp = null;
				while((temp = bufferedReader.readLine()) != null){
					stringBuffer.append(temp);
				}
				lastModify = currentModify;
				refreshTime = System.currentTimeMillis();
				return stringBuffer.toString();
			}catch(FileNotFoundException e){
				log.error("----读取文件异常，找不到文件："+e.getMessage());
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				log.error("----读取文件异常，文件读取流错误："+e.getMessage());
				e.printStackTrace();
				return null;
			}finally{
				try {
					if(bufferedReader != null){
						bufferedReader.close();
					}
				} catch (IOException e) {
					log.error("----读取文件异常，文件io流关闭错误："+e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 保存内容到文件
	 * @param content
	 * @param path
	 * @throws FileNotFoundException 
	 */
	public boolean saveFile(String content, java.io.File file){
		synchronized (obj) {
			java.io.PrintWriter writer = null;
			try{
				writer = new java.io.PrintWriter(file);
				writer.write(content);
				writer.flush();
				return true;
			}catch(Exception e){
				System.out.println("save json file exception:"+e);
				return false;
			}finally{
				try{
					if(writer != null){
						writer.close();
					}
				}catch(Exception e){
					
				}
			}
		}
	}
	
	/**
	 * 保存内容到文件
	 * @param content
	 * @param path
	 * @throws FileNotFoundException 
	 */
	public boolean saveFileForUTF(String content, java.io.File file){
		synchronized (obj) {
			FileOutputStream fos = null;
			OutputStreamWriter osw = null;
			try{
				fos = new FileOutputStream(file);
		        osw = new OutputStreamWriter(fos, "utf-8");
		        osw.write(content);
		        osw.flush();
				return true;
			}catch(Exception e){
				System.out.println("save json file exception:"+e);
				return false;
			}finally{
				try{
					if(fos != null){
						fos.close();
					}
					if(osw != null){
						osw.close();
					}
				}catch(Exception e){
					
				}
			}
		}
	}
	
	
	/**
	 * 生成静态页面  去除html 头，只生成DIV
	 * @param content
	 * @return
	 */
	public String createFileForHTML(String content){
		String resultUrl = "";
		try{
			PropKit.use("config.properties");
			String baseFileUrl = PropKit.get("base_url");// 
			String saveFilePath = PropKit.get("htmlSavePath");//保存地址
			String dirName = Jeff_DateUtils.getNowYearMonth();
			//String JsCssUrl = PropKit.get("htmlJsCssUrl");//js.css 路径
			
			
			String dir = saveFilePath + dirName + "/";
			File file = new File(new StringBuffer(String.valueOf(dir)).toString());
			if(!file.exists()){
				file.mkdirs();
			}
			String fileName = Jeff_DateUtils.getNowDateTimeForString();
			String fileNameUrl = dirName + "/" + fileName + ".html";
			
			File filehtml = new File(new StringBuffer(String.valueOf(file.getPath())).append("/").append(String.valueOf(fileName)).append(".html").toString());
			if(!filehtml.exists()){
				filehtml.createNewFile();
			}
			
			writerStream = new FileOutputStream(filehtml);
			writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
			
			
			content = "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
					+ "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">"
					+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0\" />"
					+ "<meta name=\"referrer\" content=\"origin-when-cross-origin\">"
					+ "<title>detail</title>"
					+ "<style type=\"text/css\">img {width:100%;}</style>"
					+ "</head><body>"
					+content+
					"</body></html>";
			
			writer.write(content);
			writer.close();
			
			resultUrl = baseFileUrl + "/upload/html/"+fileNameUrl;
		}catch(Exception e){
			log.error("----生成静态页面异常"+e.getMessage());
			e.printStackTrace();
		}		
		return resultUrl;
		
	}
	
	
}
